package org.robot.scm.platform.server.handler;

import static org.robot.scm.platform.server.LockKey.LAST_KEY;
import static org.robot.scm.platform.server.LockKey.LOCK_KEY;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.registry.TelegramRegistry;
import org.robot.scm.platform.server.common.LoggerHelper;
import org.robot.scm.pojos.platform.server.ExecuteParam;
import org.robot.scm.pojos.platform.server.SseParam;
import org.robot.scm.pojos.platform.server.SseParam.SseParamBuilder;
import org.robot.scm.utils.JsonHelper;

@Slf4j
public class SseLogHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/sseLog";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!exchange.getRequestMethod().equalsIgnoreCase("GET")) {
            sendFailureResponse(exchange, "请求非法");
            return;
        }

        try {
            ExecuteParam param = JsonHelper.toObject(RedisCacheHelper.get(LOCK_KEY), ExecuteParam.class);
            String last = Objects.nonNull(param) ? param.getFileKey() : RedisCacheHelper.get(LAST_KEY);
            String logger = StringUtils.isNotBlank(last) ? LoggerHelper.getLogger(last) : StringUtils.EMPTY;

            SseParamBuilder builder = SseParam.builder();
            String likeSqlKey = TelegramRegistry.likeSqlKey.get();
            if (!TelegramRegistry.likeEnvIds.isEmpty() || StringUtils.isNotBlank(likeSqlKey)) {
                ExecuteParam sqlLike = ExecuteParam.builder().fileKey(likeSqlKey).build();
                builder.sqlLike(sqlLike.mec());
            }
            builder.param(param);
            builder.logger(logger);
            sendSuccessResponse(exchange, "查询成功", JsonHelper.toJSONString(builder.build()));
        } catch (Exception e) {
            log.warn("sse error", e);
        }
    }
}
